<template>
  <!-- 弹窗对话框，根据mode的不同显示不同的标题，支持新增、编辑和查看操作 -->
  <t-drawer
    :visible="dialogVisible"
    :header="mode == 'new' ? '新增' : mode == 'edit' ? '编辑' : mode == 'view' ? '查看' : ''"
    @confirm="handleSubmit"
    @cancel="handleClose"
    @close="handleClose"
    size="50%"
  >
    <t-form ref="formInstance" :data="pageData.formData" :rules="pageData.formRules" :disabled="pageData.readOnly">
      <t-form-item label="媒体名" name="name">
        <t-input v-if="!pageData.readOnly" v-model="pageData.formData.name" />
        <div v-else class="form__text">{{ pageData.formData.name }}</div>
      </t-form-item>
      <t-form-item label="文件大小" name="size">
        <div class="form__text">{{ pageData.formData.size }} 字节</div>
      </t-form-item>
      <t-form-item label="文件路径" name="path">
        <div class="form__text">{{ pageData.formData.fullFileURI }}</div>
      </t-form-item>
      <t-form-item label="文件类型" name="path">
        <div class="form__text">{{ pageData.formData.type }}</div>
      </t-form-item>
      <t-form-item label="文件预览" v-if="mode !== 'new' && pageData.isImgPreview">
        <t-image :src="pageData.formData.fullFileURI" />
      </t-form-item>
      <t-form-item label="备注" name="remark">
        <t-textarea v-if="!pageData.readOnly" v-model="pageData.formData.remark" />
        <div v-else class="form__text">{{ pageData.formData.remark }}</div>
      </t-form-item>
    </t-form>
  </t-drawer>
</template>

<script lang="tsx" setup>
import { reactive, ref, toRaw } from "vue";
import { type FormInstanceFunctions } from "tdesign-vue-next";

import { http } from "@/utils/fetch";
// import { downloadFileStream } from "@/api/file";

import { v4 as uuidv4 } from "uuid";

import { useUserStore } from "@/stores/modules/user";

const props = defineProps({
  id: {
    type: String,
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    required: true
  }
});

const emits = defineEmits(["close"]);

const formInstance = ref<FormInstanceFunctions | null>(null);

const GET_FORM_PATH = "/media/findOne"; // 查询接口
const CREATE_FORM_PATH = ""; // 创建接口
const UPDATE_FORM_PATH = "/media/update"; // 更新接口

const userStore = useUserStore();

const pageData = reactive<Record<string, any>>({
  readOnly: false,
  formData: {
    id: "",
    createdTime: "",
    updatedTime: "",
    createdBy: "",
    updatedBy: "",
    hasDeleted: false,
    status: 0,
    remark: "",
    name: "",
    size: 0,
    fileURI: "",
    type: ""
  },
  roleSelectData: [],
  formRules: {},
  isImgPreview: false
});

// const handleDownloadFileByAuth = async () => {
//   await downloadFileStream(pageData.formData.id);
// };

/**
 * 检查文件类型是否是图片类型
 * @param {string} type - 文件的 MIME 类型
 * @returns {boolean} - 返回是否为图片类型
 */
const isImageType = (type: string) => {
  return ["image/jpeg", "image/png", "image/gif", "image/bmp", "image/webp"].includes(type);
};

/**
 * 初始化表单数据。
 * 根据不同的操作模式（新增、编辑、查看），加载不同的数据。
 * @param id - ID，用于编辑和查看模式下查询信息。
 */
const initFormData = async (id = "") => {
  if (props.mode === "new") {
    // 新增模式下，初始化表单ID和创建时间
    pageData.formData.id = uuidv4();
    pageData.formData.createdBy = userStore.userData?.id;
    pageData.formData.createdTime = new Date().toISOString();
  } else if (props.mode === "edit" || props.mode === "view") {
    // 编辑或查看模式下，根据ID查询信息
    const resultData = await http("GET", `${GET_FORM_PATH}?id=${encodeURIComponent(id)}`);
    pageData.formData = resultData.data;
    pageData.formData.fullFileURI = `/api/upload/${pageData.formData.fileURI}`;

    // 根据文件类型判断是否启用图片预览
    pageData.isImgPreview = isImageType(pageData.formData.type);
  }
};

/**
 * 初始化选择表格数据。
 * 查询所有角色信息，用于选择表格。
 */
// const initRoleSelectData = async () => {
//   const resultData = await http("POST", "/user/role/findAll", {});
//   pageData.roleSelectData = resultData.data;
// };

/**
 * 提交表单。
 * 根据不同的操作模式（新增、编辑），调用不同的接口保存信息。
 */
const handleSubmit = async () => {
  const validateResult = await formInstance?.value?.validate();
  if (validateResult === true) {
    let resultData;

    if (props.mode === "view") {
      handleClose();
    }

    const postFormData = structuredClone(toRaw(pageData.formData));

    if (props.mode === "new") {
      // 新增
      resultData = await http("POST", CREATE_FORM_PATH, postFormData);
    } else {
      // 更新
      postFormData.updatedTime = new Date().toISOString();
      postFormData.updatedBy = userStore.userData?.id;

      resultData = await http("POST", UPDATE_FORM_PATH, postFormData);
    }

    // 根据接口返回结果，提示操作成功或失败，并关闭对话框
    if (resultData.code === 200) {
      emits("close", "success");
    }
  }
};

const handleClose = () => {
  // 关闭对话框，并返回取消操作标识
  emits("close", "cancel");
};

// 如果是查看模式，设置表单为只读
if (props.mode == "view") {
  pageData.readOnly = true;
}

// 初始化表单数据，根据传入的 ID
initFormData(props.id);
// initRoleSelectData();
</script>
